// JS桥接插件接口
export function getSmsList() {
  return new Promise((resolve, reject) => {
    if (!plus || !plus.android) {
      return reject('非App环境或plus对象未准备好');
    }

    const uniSmsLog = uni.requireNativePlugin('uniSmsLog');

    // 先申请权限
    const main = plus.android.runtimeMainActivity();
    const Context = plus.android.importClass('android.content.Context');
    const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
    const permission = 'android.permission.READ_SMS';

    let hasPermission = plus.android.invoke(main, 'checkSelfPermission', permission) === PackageManager.PERMISSION_GRANTED;

    function requestPermission(callback) {
      plus.android.requestPermissions(
        [permission],
        function(result) {
          if (result && result[0] === 'granted') {
            callback(true);
          } else {
            callback(false);
          }
        },
        function(err) {
          console.error('权限请求失败:', err);
          callback(false);
        }
      );
    }

    function fetchSms() {
      uniSmsLog.getSmsList((res) => {
        if (typeof res === 'string' && res.startsWith('error')) {
          reject(res);
        } else {
          resolve(res);
        }
      });
    }

    if (hasPermission) {
      fetchSms();
    } else {
      requestPermission((granted) => {
        if (granted) {
          fetchSms();
        } else {
          reject('短信权限被拒绝');
        }
      });
    }
  });
}
